package com.woniuxy.microseckillserver.listener;

import com.alibaba.fastjson.JSONObject;
import com.woniuxy.microcommonserver.bean.seckill_lk.SeckillGoodsInfo;
import com.woniuxy.microcommonserver.bean.seckill_lk.SellRequest;
import com.woniuxy.microseckillserver.service.ISeckillService;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.LinkedHashMap;

/**
 * @Author: 刘康
 * @Date: 2021/1/23 16:44
 * @Description:
 */
@Component
public class OrderListener {

    @Resource
    private HashOperations hashOperations;
    @Resource
    private ISeckillService seckillServiceImpl;
    @Resource
    private RedissonClient redissonClient;

    @RabbitHandler
    @RabbitListener(queues = {"order.queue"})
    public void orderHandler(String msg){
        //处理消息
        System.out.println("OrderQueueListener=====" + msg);

        SellRequest request = JSONObject.parseObject(msg).toJavaObject(SellRequest.class);
        /*预扣库存（从Redis中）*/
        for (int i = new Date().getDate(); i >0 ; i--) {
            String hashKey = "seckillGoods" + i;

            LinkedHashMap hashMap = (LinkedHashMap) hashOperations.get(hashKey,request.getGoodsID().toString());

            if (hashMap != null){
                String str = JSONObject.toJSONString(hashMap);
                System.out.println(str);
                SeckillGoodsInfo seckillGoodsInfo = JSONObject.parseObject(str, SeckillGoodsInfo.class);

                seckillGoodsInfo.setStock(seckillGoodsInfo.getStock() -1);
                hashOperations.put("coupons",request.getGoodsID().toString(),seckillGoodsInfo);

                //向数据库真实产生订单(openFeign调用订单微服务)
              seckillServiceImpl.order(request);

                return;
            }

        }
    }




    /**
     * 监听死信出口队列
     * 该队列中的消息，都是经过延迟后的数据
     * @param msg
     */
    @RabbitHandler
    @RabbitListener(queues = {"dleReceiveQueue"})
    public void PayHandler(String msg){
        //将Json字符串转换给Java对象
        SellRequest sellRequest = JSONObject.parseObject(msg,SellRequest.class);
        //判断订单的支付状态(openFeign)
//        int payStatus = seckillServiceImpl.checkPayStatus(orderInfo.getId());
        int payStatus=0;
        if(payStatus > 0){
            //如果已支付（确认）
            System.out.println(sellRequest.getGoodsID() + "，已生效！！！");
        }else{
            //如果未支付（订单删除，库存回滚，缓存+1,OpenFeign）
//            orderServiceImpl.deleteOrderInfo(orderInfo.getId());
//            orderServiceImpl.updateCoupon(orderInfo.getFkCouponId());
            //加个锁（防第2次更新丢失问题）
            RLock rlock = redissonClient.getLock("lock_"+sellRequest.getGoodsID());
            rlock.lock();//获得Redis分布式锁

            //redis添加库存
            for (int i = new Date().getDate(); i >0 ; i--) {
                String hashKey = "seckillGoods" + i;

                LinkedHashMap hashMap = (LinkedHashMap) hashOperations.get(hashKey,sellRequest.getGoodsID().toString());

                if (hashMap != null){
                    String str = JSONObject.toJSONString(hashMap);
                    System.out.println(str);
                    SeckillGoodsInfo seckillGoodsInfo = JSONObject.parseObject(str, SeckillGoodsInfo.class);

                    seckillGoodsInfo.setStock(seckillGoodsInfo.getStock() +1);
                    hashOperations.put(hashKey,sellRequest.getGoodsID().toString(),seckillGoodsInfo);

                    return;
                }

            }

            rlock.unlock();//释放Redis分布式锁
        }
    }

}
